package com.kinyx.framework.db.sentence.res;

import java.util.ArrayList;
import java.util.List;

import com.kinyx.framework.db.configs.DBConfigs;
import com.kinyx.framework.utils.KArrayUtils;
import com.kinyx.framework.utils.KListUtils;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/**
 * 条件子句
 */
@NoArgsConstructor(access = AccessLevel.PACKAGE)
class _Conditions extends _SentenceWithParams {

	/** 条件列表 */
	private List<Condition> conditions = new ArrayList<>();

	@Override
	public String getSentence(final DBConfigs configs, final boolean isSQL, final boolean withTableAlias) {
		return KListUtils.join(this.conditions, " ", (condition, index) -> {
			final StringBuilder sql = new StringBuilder();
			if (index != 0) {// 首个条件不拼接类型
				sql.append(Boolean.FALSE.equals(condition.getConditionType()) ? "OR" : "AND").append(" ");
			}
			return sql.append(condition.getSentence(configs, isSQL, withTableAlias)).toString();
		});
	}

	@Override
	public List<Object> getParams() {
		final List<Object> list = new ArrayList<>();
		this.conditions.forEach(condition -> {
			list.addAll(condition.getParams());
		});
		return list;
	}

	void add(final Condition condition) {
		this.conditions.add(condition);
	}

	void addAll(final Condition... conditions) {
		if (!KArrayUtils.isEmpty(conditions)) {
			this.conditions.addAll(KArrayUtils.toList(conditions));
		}
	}

}
